﻿//for configuration tab
var list_id;
var list_name;
var type_id;
var type_name;
var precision;

//for dimension sub-tab config table : X_MASTER_LIST
function loadConfigDimdata() {

    var url = "ConfigCallback.aspx?operation=get_XMasterList";

    $.ajax({
        async: true,
        type: 'GET',
        url: "ConfigCallback.aspx?operation=get_XMasterListColumns",
        data: "",
        dataType: "json",
        success: function (result) {
            $("#dtXMasterList").GridUnload(); // destroy the grid saving the table and pager
            var editurl = "table=XMasterList";
            //call fill grid for dimension table          
            fillgridDimNav(result, "#dtXMasterList", "#pgXMasterList", "800px", "350px", "Config Data", editurl, url);
        },
        error: function (x, e) {
            ////debugger
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}

//for dimension sub tab columns : X_MASTER_LIST_COLUMNS
function loadConfigDimColdata() {

    //debugger; 

    if (list_id != jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow')) {

        list_id = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');

        if (list_id == null || list_id == "undefined") {
            alert("Please Select dimension to show columns");
            return false;
        }
        else {

            var selrow = jQuery("#dtXMasterList").getRowData(list_id);
            ////debugger;
            list_name = jQuery("#dtXMasterList").getRowData(list_id)['LIST_NAME'];
            var url = "ConfigCallback.aspx?operation=get_XMasterListCol&list_id=" + list_id;

            $.ajax({
                async: true,
                type: 'GET',
                url: "ConfigCallback.aspx?operation=get_XMasterListColColumns&list_id=" + list_id,
                data: "",
                success: function (result) {
                    //debugger;
                    var arr = result.split("|");
                    //alert(eval('(' + arr[0] + ')'));
                    if (arr[1] == 1) {
                        $("#CSubmit_CrTable").attr('value', 'Edit Table');
                    }
                    else {
                        $("#CSubmit_CrTable").attr('value', 'Create Table');
                    }

                    $("#dtXMasterListCol").GridUnload(); // destroy the grid saving the table and pager                 
                    var editurl = "table=XMasterListCol&list_id=" + list_id;

                    //alert("ll");

                    //call fill grid for dimension table columns    
                    fillgridDimCol(eval('(' + arr[0] + ')'), "#dtXMasterListCol", "#pgXMasterListCol", "800px", "350px", "Configure Columns for " + list_name, editurl, url);
                    //if columns are there show create table button
                    //                    if ($("#dtXMasterListCol").getGridParam("reccount") > 0) {
                    //                        $("#CSubmit_CrTable").show();
                    //                    }
                    //                    else {
                    //                        //debugger;
                    //                        $("#CSubmit_CrTable").hide();
                    //                        // if ($("#dtXMasterListCol").getGridParam("reccount") > 0) {
                    //                        //ask naval for grid height if columns are not there 
                    //                        jQuery(".ui-jqgrid-bdiv", "#gview_dtXMasterListCol").css('height', '0px');
                    //                    }
                    ////debugger
                    //                    if ($("#dtXMasterListCol").getGridParam("reccount") == 0) {
                    //                        $("#CSubmit_CrTable").hide();
                    //                        // if ($("#dtXMasterListCol").getGridParam("reccount") > 0) {
                    //                        //ask naval for grid height if columns are not there 
                    //                        //jQuery(".ui-jqgrid-bdiv", "#gview_dtXMasterListCol").css('height', '0px');
                    //                    }
                    //                    else {
                    //                        //debugger;
                    //                        $("#CSubmit_CrTable").show();
                    //                    }

                },
                error: function (x, e) {
                    alert(x.readyState + " " + x.status + " " + e.msg);
                }
            });
        }
    }
}

//original before url implementation
////to fill jqgird - function with Add , Edit and Delete for dimension 
//function fillgridDimNav(result, tblname, pgname, gWidth, gHeight, caption, editurll) {
//    ////debugger;
//    var colD = result.datarow, colN = result.columns, colM = result.colModelList;

//    jQuery(tblname).jqGrid({
//        data: colD,
//        datatype: 'local',
//        gridview: true,
//        colNames: colN,
//        colModel: colM,
//        caption: caption,
//        editurl: "ConfigCallback.aspx?" + editurll,
//        rowNum: 10,
//        pager: pgname,
//        sortname: result.primarykey,
//        sortorder: "desc",
//        width: "800px",
//        height: "100%",
//        scrollOffset: 18,
//        closeAfterEdit: true,
//        ignoreCase: true,
//        loadComplete: function (data) {
//            ////debugger;
//            jQuery(tblname).hideCol(result.primarykey);
//            jQuery(tblname).setGridWidth(980, true);

//            if (tblname == "#dtXMasterListCol") {
//                //set dataEvents for  dropdown data_type
//                var dataType = "nvarchar:nvarchar;varchar:varchar;float:float;int:int;datetime:datetime;char:char";
//                var appendtagPrec = "<font id='fprec' style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

//                $(tblname).setColProp('DATA_TYPE', {
//                    editoptions: { "style": "width:160px",
//                        "size": 400,
//                        value: dataType,
//                        dataEvents: [{ type: 'change',
//                            fn: function (e) {
//                                var val = $(e.target).val();
//                                var relTo = $("#PRECISION", "#FrmGrid_dtXMasterListCol");
//                                ////debugger;
//                                if (val == "float" || val == "int" || val == "datetime") {
//                                    $("#dtXMasterListCol").setColProp('PRECISION', { editrules: { required: false} });
//                                    $('#fprec', '#FrmGrid_dtXMasterListCol').remove();
//                                }
//                                else {
//                                    $("#dtXMasterListCol").setColProp('PRECISION', { editrules: { required: true} });
//                                    $('#fprec', '#FrmGrid_dtXMasterListCol').remove();
//                                    $(appendtagPrec).insertAfter(relTo);
//                                }
//                            }
//                        }]

//                    }
//                });
//                //
//                //set dataEvents for check-box is_primary
//                // if primary is true then it can't be null so 
//                // check is_req and make it disable
//                $(tblname).setColProp('IS_PRIMARY', {
//                    editoptions: {
//                        dataEvents: [{ type: 'change',
//                            fn: function (e) {
//                                ////debugger;
//                                var val = $(e.target);
//                                if ($(e.target).attr('checked')) {
//                                    $("#IS_REQUIRED", "#FrmGrid_dtXMasterListCol").attr('checked', 'checked');
//                                    $("#IS_REQUIRED", "#FrmGrid_dtXMasterListCol").attr("disabled", "disabled");                                  
//                                }
//                                else {
//                                    $('#IS_REQUIRED', "#FrmGrid_dtXMasterListCol").removeAttr("disabled");
//                                }
//                            }
//                        }]
//                    }
//                });
//                //
//            }

//        },
//        onSelectRow: function (rowid) {
//            //if _xref ,_grey tables exist disable delete button else
//            //enable table
//            if (tblname == "#dtXMasterList") {
//                var IsTableCreated = $(this).jqGrid('getCell', rowid, 'IsTableCreated');
//                if (IsTableCreated == "1") {
//                    //alert("Related Tables exists ! Can't Delete Table !");
//                    $("#del_" + this.id).addClass('ui-state-disabled');
//                }
//                else {
//                    $("#del_" + this.id).removeClass('ui-state-disabled');
//                }
//            }

//            //if _xref ,_grey tables exist disable delete button else
//            //enable table
//            if (tblname == "#dtXMasterListCol") {
//                ////debugger;
//                var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');
//                var IsTableCreated = jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated');
//                if (IsTableCreated == "1") {
//                    //alert("Related Tables exists ! Can't Delete Table !");
//                    $("#del_" + this.id).addClass('ui-state-disabled');
//                }
//                else {
//                    $("#del_" + this.id).removeClass('ui-state-disabled');
//                }
//            }
//            return true;

//        },
//        loadError: function (xhr, status, error) {
//            ////debugger;
//            alert('error');
//        }
//    });

//    //navigation grid setting
//    navGriddDim(tblname, pgname);
//}

//to fill jqgird - function with Add , Edit and Delete for dimension 
function fillgridDimNav(result, tblname, pgname, gWidth, gHeight, caption, editurll, url) {
    // //debugger;
    var colN = result.columns, colM = result.colModelList;

    jQuery(tblname).jqGrid({
        // data: colD,
        // datatype: 'local',
        url: url,
        datatype: 'json',
        gridview: true,
        colNames: colN,
        colModel: colM,
        caption: caption,
        editurl: "ConfigCallback.aspx?" + editurll,
        rowNum: 10,
        pager: pgname,
        sortname: result.primarykey,
        sortorder: "desc",
        width: "800px",
        height: "100%",
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        viewrecords: true,
        loadComplete: function (data) {
            ////debugger;
            jQuery(tblname).hideCol(result.primarykey);
            jQuery(tblname).setGridWidth("900", true);
        },
        onSelectRow: function (rowid) {
            //if _xref ,_grey tables exist disable delete button else
            //enable table
            if (tblname == "#dtXMasterList") {
                var IsTableCreated = $(this).jqGrid('getCell', rowid, 'IsTableCreated');
                if (IsTableCreated == "1") {
                    //alert("Related Tables exists ! Can't Delete Table !");
                    $("#del_" + this.id).addClass('ui-state-disabled');
                }
                else {
                    $("#del_" + this.id).removeClass('ui-state-disabled');
                }
            }

            return true;
        },
        loadError: function (xhr, status, error) {
            ////debugger;
            alert('error');
        }
    });

    //navigation grid setting
    navGriddDim(tblname, pgname);
}


//to fill jqgird - function with Add , Edit and Delete for dimension col 
function fillgridDimCol(result, tblname, pgname, gWidth, gHeight, caption, editurll, url) {
    //debugger;

    var colN = result.columns, colM = result.colModelList;

    jQuery(tblname).jqGrid({
        // data: colD,
        // datatype: 'local',
        url: url,
        datatype: 'json',
        gridview: true,
        colNames: colN,
        colModel: colM,
        caption: caption,
        editurl: "ConfigCallback.aspx?" + editurll,
        //rowNum: 10,
        loadonce: true,
        pager: pgname,
        sortname: result.primarykey,
        sortorder: "asc",
        width: "800px",
        height: "100%",
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        viewrecords: true,
        loadComplete: function (data) {
            //debugger;
            jQuery(tblname).hideCol(result.primarykey);
            jQuery(tblname).setGridWidth("900", true);
            //debugger;
            if (tblname == "#dtXMasterListCol") {

                if ($("#dtXMasterListCol").getGridParam("reccount") == 0) {
                    $("#CSubmit_CrTable").hide();
                    //ask naval for grid height if columns are not there 
                    //jQuery(".ui-jqgrid-bdiv", "#gview_dtXMasterListCol").css('height', '0px');
                }
                else {
                    //debugger;
                    $("#CSubmit_CrTable").show();
                    //jQuery(".ui-jqgrid-bdiv", "#gview_dtXMasterListCol").css('height', '100%');
                }
                //set dataEvents for  dropdown data_type
                var dataType = "nvarchar:nvarchar;varchar:varchar;float:float;int:int;bigint:bigint;datetime:datetime;char:char";
                var appendtagPrec = "<font id='fprec' style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";


                $(tblname).setColProp('DATA_TYPE', {
                    editoptions: { "style": "width:160px",
                        "size": 400,
                        value: dataType,
                        dataEvents: [{ type: 'change',
                            fn: function (e) {
                                var val = $(e.target).val();
                                var relTo = $("#PRECISION", "#FrmGrid_dtXMasterListCol");
                                ////debugger;
                                if (val == "float" || val == "int" || val == "datetime") {
                                    $("#dtXMasterListCol").setColProp('PRECISION', { editrules: { required: false} });
                                    $('#fprec', '#FrmGrid_dtXMasterListCol').remove();
                                }
                                else {
                                    $("#dtXMasterListCol").setColProp('PRECISION', { editrules: { required: true} });
                                    $('#fprec', '#FrmGrid_dtXMasterListCol').remove();
                                    $(appendtagPrec).insertAfter(relTo);
                                }
                            }
                        }]
                    }
                });
                //
                //set dataEvents for check-box is_primary
                // if primary is true then it can't be null so 
                // check is_req and make it disable
                $(tblname).setColProp('IS_PRIMARY', {
                    editoptions: {
                        dataEvents: [{ type: 'change',
                            fn: function (e) {
                                ////debugger;
                                var val = $(e.target);
                                if ($(e.target).attr('checked')) {
                                    $("#IS_REQUIRED", "#FrmGrid_dtXMasterListCol").attr('checked', 'checked');
                                    $("#IS_REQUIRED", "#FrmGrid_dtXMasterListCol").attr("disabled", "disabled");
                                }
                                else {
                                    $('#IS_REQUIRED', "#FrmGrid_dtXMasterListCol").removeAttr("disabled");
                                }
                            }
                        }]
                    }
                });
                //
            }
        },
        onSelectRow: function (rowid) {

            //if _xref ,_grey tables exist disable delete button else
            //enable table
            if (tblname == "#dtXMasterListCol") {
                ////debugger;
                var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');
                var IsTableCreated = jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated');
                if (IsTableCreated == "1") {
                    //alert("Related Tables exists ! Can't Delete Table !");
                    $("#del_" + this.id).addClass('ui-state-disabled');
                }
                else {
                    $("#del_" + this.id).removeClass('ui-state-disabled');
                }
            }
            return true;

        },
        loadError: function (xhr, status, error) {
            ////debugger;
            alert('error');
        }
    });

    //navigation grid setting
    navGriddDim(tblname, pgname);
}


//navigation bar of grid- setting metohd
function navGriddDim(tblname, pgname) {
    ////debugger;
    jQuery(tblname).jqGrid('navGrid', pgname, { del: true, edit: true, add: true, search: true },
   {
       //edit
       afterSubmit: afterSubCommon,
       closeAfterEdit: true,
       reloadAfterSubmit: false,
       width: "500",
       modal: true,
       onInitializeForm: function (formid) {
           // //debugger;         
           //for  * sign for mandatory field  and datepicker
           colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
           var arr = tblname.split('#');
           colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;

           //common method for suffice star in add/edit dialog box
           SufficeStar(colModelLocal, formid);
       },
       beforeSubmit: function (postdata, formid) {
           //debugger;
           if (tblname == "#dtXMasterListCol") {
               if (parseInt(postdata["PRECISION"]) < parseInt(precision)) {//parseInt("50")< parseInt("100")
                   alert("Precision cannot be smaller !");
                   return false;
               }
               else {
                   return [true, ''];
               }
           }
       },
       beforeShowForm: function (formid) {
           //in edit mode for X_MASTER_LIST disable abbr column
           if (tblname == "#dtXMasterList") {
               $('#TABLE_ABBR', formid).attr("disabled", "disabled");
               //color:#DDD9D9 for disable
           }

           ////debugger;
           if (tblname == "#dtXMasterListCol") {
               //put condition for if tables are created 
               var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');

               if (jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated') == "1") {
                   $('#FIELD_NAME', formid).attr("disabled", "disabled");
                   $('#DATA_TYPE', formid).attr("disabled", "disabled");

                   //IS_PRIMARY
                   $('#IS_PRIMARY', formid).attr("disabled", "disabled");
                   $('#CONTROL_TYPE', formid).attr("disabled", "disabled");

                   if ($('#IS_REQUIRED', formid).attr('checked')) {
                       //enable
                       if ($('#IS_PRIMARY', formid).attr('checked')) {
                           $('#IS_REQUIRED', formid).attr("disabled", "disabled");
                       }
                       else {
                           $('#IS_REQUIRED', formid).removeAttr("disabled");
                       }
                   }
                   else {

                       $('#IS_REQUIRED', formid).attr("disabled", "disabled");
                   }

                   if ($('#IS_PRIMARY', formid).attr('checked')) {
                       $('#IS_ACTIVE', formid).attr("disabled", "disabled");
                   }
                   else {
                       $('#IS_ACTIVE', formid).removeAttr("disabled");
                   }
               }

               precision = $('#PRECISION', formid).val();

               ///put mandatory editrule depending on condition             
               var relTo = $("#PRECISION", formid);
               var appendtagPrec = "<font id='fprec' style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";
               var val = $('#DATA_TYPE', formid).attr('value');

               if (val == "float" || val == "int" || val == "datetime") {
                   $("#dtXMasterListCol").setColProp('PRECISION', { editrules: { required: false} });
                   $('#fprec', '#FrmGrid_dtXMasterListCol').remove();
               }
               else {
                   $("#dtXMasterListCol").setColProp('PRECISION', { editrules: { required: true} });
                   $('#fprec', '#FrmGrid_dtXMasterListCol').remove();
                   $(appendtagPrec).insertAfter(relTo);
               }
               ////
           }
       }
   },
   {//new

       afterSubmit: function (response) {
           ////debugger;
           var arr = response.responseText.split("|");

           if (arr[0] == "false") {
               //if (response.responseText == "false") {               
               //alert(response.responseText);              
               if (arr[1] != "") {
                   return [false, arr[1]]
               }
               else {
                   return [false, "some error in save !"]
               }
           }
           else {
               if (tblname == "#dtXMasterListCol") {
                   showhideCreateButton($("#dtXMasterListCol").getGridParam("reccount") + 1);
               }
               return [true, "saved successfully !", response.responseText]
           }

       },
       closeAfterAdd: true,
       reloadAfterSubmit: false,
       width: "500",
       modal: true,
       onInitializeForm: function (formid) {
           ////debugger;
           //for  * sign for mandatory field  and datepicker
           colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
           var arr = tblname.split('#');
           colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;
           //common method for suffice star in add/edit dialog box
           SufficeStar(colModelLocal, formid);
       },
       beforeShowForm: function (formid) {
           ////debugger;
           if (tblname == "#dtXMasterList") {
               $('#TABLE_ABBR', formid).removeAttr("disabled");
           }

           //put condition for if tables are created 
           if (tblname == "#dtXMasterListCol") {
               var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');

               //new column should be by default active
               $('#IS_ACTIVE', formid).attr('checked', 'checked');

               if (jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated') == "1") {

                   $('#FIELD_NAME', formid).removeAttr("disabled");
                   $('#DATA_TYPE', formid).removeAttr("disabled");

                   $('#IS_REQUIRED', formid).attr("disabled", "disabled");
                   $('#IS_PRIMARY', formid).attr("disabled", "disabled");

               }
               else {
                   if ($('#IS_REQUIRED', formid).attr("disabled")) {
                       $('#IS_REQUIRED', formid).removeAttr("disabled");
                   }

                   if ($('#IS_PRIMARY', formid).attr("disabled")) {
                       $('#IS_PRIMARY', formid).removeAttr("disabled");
                   }

                   if ($('#CONTROL_TYPE', formid).attr("disabled")) {
                       $('#CONTROL_TYPE', formid).removeAttr("disabled");
                   }

                   if ($('#IS_ACTIVE', formid).attr("disabled")) {
                       $('#IS_ACTIVE', formid).removeAttr("disabled");
                   }
               }

               ///put mandatory editrule depending on condition             
               var relTo = $("#PRECISION", formid);
               var appendtagPrec = "<font id='fprec' style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";
               $("#dtXMasterListCol").setColProp('PRECISION', { editrules: { required: true} });
               $('#fprec', '#FrmGrid_dtXMasterListCol').remove();
               $(appendtagPrec).insertAfter(relTo);
               ////

           }
       }
   },
    {//delete
        afterSubmit: function (response) {
            // //debugger;
            if (response.responseText == "true") {
                if (tblname == "#dtXMasterListCol") {
                    showhideCreateButton($("#dtXMasterListCol").getGridParam("reccount") - 1);
                    //refresh columns grid                   
                }
                if (tblname == "#dtXMasterList") {
                    $("#dtXMasterListCol").GridUnload(); // destroy the grid saving the table and pager   
                    $("#CSubmit_CrTable").hide();
                }

                return [true, "deleted successfully !"]
            }
            else if (response.responseText == "false") {
                return [false, "some error in delete !"]
            }
            else {
                ////debugger;
                var arr = response.responseText.split(":");
                $("#hidListCol").val(arr[1]);
                //return [false, response.responseText]
                return [false, arr[1]]
            }
        },
        closeAfterEdit: true,
        reloadAfterSubmit: false,
        beforeShowForm: function (formid) {
            ////debugger;
            if (tblname == "#dtXMasterList") {
                list_id = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');

                if (jQuery("#dtXMasterList").getRowData(list_id)['IsTableCreated'] == "1") {
                    alert("Related Tables exists ! Can't Delete Table !");
                    return false;
                }
            }
        }
    },
    {//complex search
        multipleSearch: true,
        multipleGroup: true,
        showQuery: true
    }
);
}


//create table of _xref, _grey,_history
function CreateDimConfigTable() {
    ////debugger;  
    //validate for at least 1 primary key
    if ($("#CSubmit_CrTable")[0].value == "Create Table") {
        //        var col = jQuery("#dtXMasterListCol").jqGrid('getCol', 'IS_PRIMARY', false, '');
        //        if (jQuery.inArray("Yes", col) == -1) {
        //            alert("Please put at least one primary key column !");
        //            return false;
        //        }
        //        else {
        if ($("#dtXMasterListCol").getGridParam("reccount") > 0) {

            var msg = " Do you want to create the table for " + list_name;
            if (confirm(msg) === true) {
                $.ajax({
                    async: true,
                    type: 'GET',
                    url: "ConfigCallback.aspx?operation=CreateDimConfigTable&list_id=" + list_id,
                    data: "",
                    dataType: "json",
                    success: function (result) {
                        if (result == true) {
                            alert("Created Successfully !");
                            $("#CSubmit_CrTable").attr('value', 'Edit Table');
                        }
                        else {
                            alert("Some  error in creation of table !");
                        }
                    },
                    error: function (x, e) {
                        alert(x.readyState + " " + x.status + " " + e.msg);
                    }
                });
            }
            else {
                return false;
            }

        }
        else {
            alert("Please put at least 1 column to create table !");
            return false;
        }
        //}

    }
    else {
        alert('not done--');
    }
}


//ReverseEngConfigTable
function ReverseEngConfigTable() {

    var left = (screen.width / 2) - (900 / 2);
    var top = ((screen.height / 2) - (550 / 2) - 20);

    var DialogOptions = "center=yes; Scrollbar=No; dialogWidth=900px; dialogHeight=550px; Help=No; Status=No; Resizable=Yes;dialogTop=" + top + "px;dialogLeft=" + left + "px;";
    var OpenUrl = "ReEngineering.aspx";
    var ret = window.showModalDialog(OpenUrl, "Yes", DialogOptions);
    ////debugger
    //if added the relation refresh grid of both exist and un-assigned
    //if (typeof (ret) != "true") {
    if (ret == "true") {

        //fill dim table
        loadConfigDimdata();
        //unload col grid
        $("#dtXMasterListCol").GridUnload(); // destroy the grid saving the table and pager
        $("#CSubmit_CrTable").hide();

    }

    //    // //debugger;
    //    $.ajax({
    //        async: true,
    //        type: 'GET',
    //        url: "ConfigCallback.aspx?operation=ReverseEngConfigTable",
    //        data: "",
    //        dataType: "json",
    //        success: function (result) {
    //            ////debugger;
    //            if (result == true) {
    //                alert("Created Successfully !");
    //            }
    //            else {
    //                alert("Some  error in creation of table !");
    //            }
    //        },
    //        error: function (x, e) {
    //            ////debugger;
    //            alert(x.readyState + " " + x.status + " " + e.msg);
    //        }
    //    });

}

//if columns are greater than 1 
//then show else hide the button
function showhideCreateButton(reccnt) {
    ////debugger;
    if (reccnt > 0) {
        $("#CSubmit_CrTable").show();
    }
    else {
        $("#CSubmit_CrTable").hide();
    }

    var tblrowid = jQuery("#dtXMasterList").jqGrid('getGridParam', 'selrow');
    var IsTableCreated = jQuery("#dtXMasterList").jqGrid('getCell', tblrowid, 'IsTableCreated');

    if (IsTableCreated == "1") {
        $("#CSubmit_CrTable").attr('value', 'Edit Table');
    }
    else {
        $("#CSubmit_CrTable").attr('value', 'Create Table');
    }
}

///////////
//for User sub-tab
///////////

//for user type
function loadConfigUserTypedata() {

    $.ajax({
        async: true,
        type: 'GET',
        //url: "ConfigCallback.aspx?operation=get_UserType",
        url: "ConfigCallback.aspx?operation=get_UserTypeCol", //get_UserTypeCol
        data: "",
        dataType: "json",
        success: function (result) {
            //alert("true");
            ////debugger;
            $("#dtMUserType").GridUnload(); // destroy the grid saving the table and pager
            // var editurl = "ConfigCallback.aspx&table=XMasterList";
            var editurl = "table=UserType";
            var url = "ConfigCallback.aspx?operation=get_UserTypeData";

            fillgridUserNav(result, "#dtMUserType", "#pgMUserType", "800px", "350px", "Config Data", editurl, url);
        },
        error: function (x, e) {
            ////debugger;
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}

function loadConfigUserdata() {

    ////debugger;
    if (type_id != jQuery("#dtMUserType").jqGrid('getGridParam', 'selrow')) {

        type_id = jQuery("#dtMUserType").jqGrid('getGridParam', 'selrow');

        if (type_id == null || type_id == "undefined") {
            alert("Please Select User Type to show users");
            return false;
        }
        else {

            var selrow = jQuery("#dtMUserType").getRowData(type_id);
            type_name = jQuery("#dtMUserType").getRowData(type_id)['USER_TYPE_NAME'];
            var url = "ConfigCallback.aspx?operation=get_UserData&type_id=" + type_id;

            $.ajax({
                async: true,
                type: 'GET',
                url: "ConfigCallback.aspx?operation=get_UserDataCol&type_id=" + type_id,
                data: "",
                success: function (result) {
                    ////debugger;                
                    $("#dtMUser").GridUnload(); // destroy the grid saving the table and pager
                    var editurl = "table=User&type_id=" + type_id;
                    fillgridUserNav(eval('(' + result + ')'), "#dtMUser", "#pgMUser", "800px", "350px", "Users for " + type_name, editurl, url);
                },
                error: function (x, e) {
                    ////debugger;
                    alert(x.readyState + " " + x.status + " " + e.msg);
                }
            });
        }
    }
}

//to fill jqgird -User -with Add , Edit and Delete
function fillgridUserNav(result, tblname, pgname, gWidth, gHeight, caption, editurll, url) {
    ////debugger;
    var colD = result.datarow, colN = result.columns, colM = result.colModelList;

    jQuery(tblname).jqGrid({
        //data: colD,
        //datatype: 'local',
        //datatype: "json",
        url: url,
        datatype: 'json',
        gridview: true,
        colNames: colN,
        colModel: colM,
        caption: caption,
        editurl: "ConfigCallback.aspx?" + editurll,
        rowNum: 10,
        pager: pgname,
        sortname: result.primarykey,
        sortorder: "desc",
        width: "800px",
        height: "100%",
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        loadComplete: function (data) {
            //debugger;
            //alert(jQuery(".ui-jqgrid-bdiv").css('height'));
            jQuery(tblname).hideCol(result.primarykey);
            jQuery(tblname).setGridWidth("900", true);
        },
        onSelectRow: function (rowid) {
            if (tblname == "#dtMUserType") {
                var hasUser = $(this).jqGrid('getCell', rowid, 'hasUser');
                if (hasUser == "1") {
                    //alert("Related Tables exists ! Can't Delete Table !");
                    $("#del_" + this.id).addClass('ui-state-disabled');
                }
                else {
                    $("#del_" + this.id).removeClass('ui-state-disabled');
                }
            }
            return true;

        },
        loadError: function (xhr, status, error) {
            ////debugger;
            alert('error');
        }
    });

    navGriddUser(tblname, pgname);
}


function navGriddUser(tblname, pgname) {
    ////debugger;
    jQuery(tblname).jqGrid('navGrid', pgname, { del: true, edit: true, add: true, search: true },
   {//edit

       afterSubmit: afterSubCommon,
       closeAfterEdit: true,
       reloadAfterSubmit: false,
       width: "500",
       modal: true,
       onInitializeForm: function (formid) {
           ////debugger;         
           //for  * sign for mandatory field  and datepicker
           colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
           var arr = tblname.split('#');
           colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;
           //common method for suffice star in add/edit dialog box + datepicker
           SufficeStar(colModelLocal, formid);
       }
   },
   {//new
       // afterSubmit: afterSub,
       afterSubmit: function (response) {
           var arr = response.responseText.split("|");
           if (arr[0] == "false") {
               //if (response.responseText == "false") {               
               //alert(response.responseText);               
               if (arr[1] != "") {
                   return [false, arr[1]]
               }
               else {
                   return [false, "some error in save !"]
               }
           }
           else {
               return [true, "saved successfully !", response.responseText]
           }
       },
       closeAfterAdd: true,
       reloadAfterSubmit: false,
       width: "500",
       modal: true,
       onInitializeForm: function (formid) {
           ////debugger;
           //for  * sign for mandatory field  and datepicker
           colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
           var arr = tblname.split('#');
           colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;
           //common method for suffice star in add/edit dialog box + datepicker
           SufficeStar(colModelLocal, formid);
       },
       beforeShowForm: function (formid) {
           ////debugger;
           if (tblname == "#dtMUser") {
               $('#IS_ACTIVE', formid).attr('checked', 'checked');
           }
       }
   },
   {//delete
       afterSubmit: function (response) {
           ////debugger;
           if (response.responseText == "true") {
               if (tblname == "#dtMUserType") {
                   //refresh columns grid
                   $("#dtMUser").GridUnload(); // destroy the grid saving the table and pager
               }
               return [true, "deleted successfully !"]
           }
           else if (response.responseText == "false") {
               return [false, "some error in delete !"]
           }
           else {
               ////debugger;
               var arr = response.responseText.split(":");
               //return [false, response.responseText]
               return [false, arr[1]];
           }
       },
       closeAfterEdit: true,
       reloadAfterSubmit: false
   },
    {//complex search
        multipleSearch: true,
        multipleGroup: true,
        showQuery: true
    }
);
}

//end of user tab

